<template>
  <div>
    <!-- 核心功能: 1.预览, 2.数量控制, 3.删除,  4.上传,  进度条 -->

    <!--
    action:默认图片上传的地址  设置为空或#
    list-type:picture-card   照片墙
    file-list:文件列表数据 数组
    on-preview：预览属性 会触发预览的钩子函数
    on-remove: 删除 会触发删除的钩子函数
   -->
    <el-upload
      action=""
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePreview"
      :class="{disabled:fileComputed}"
      :on-remove="handleRomove"
      :http-request="handleRequest"
      :on-change="handleChange"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="srcUrl" alt="" style="width:100%;">
    </el-dialog>
  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKID3waz94j9KFvLWR6WgaFenhLktnRqzsWu', // 身份识别ID
  SecretKey: 'A4j8HAoDMFsGOGtGNEqCIuGMDoAG7i38'// 身份秘钥
})
export default {
  name: 'UploadImage',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      showDialog: false,
      srcUrl: ''
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length >= this.limit
    },
    // 是否全部上传成功了
    uploadAllSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    handlePreview(file) {
      // console.log(file)
      this.showDialog = true
      this.srcUrl = file.url
    },
    // file:是删除的文件
    // fileList:是删除后的结构中的数组
    // this.fileList:是数据中的数组
    handleRomove(file, fileList) {
      // 方案一:
      // this.fileList = [...fileList]
      // 方案二:
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },
    handleRequest(obj) {
      // 执行上传操作
      const o = this.fileList.find(item => item.uid === obj.file.uid)
      cos.putObject({
        Bucket: 'sherther-78-1309207531', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Math.ceil(Math.random() * 1000) + '-' + obj.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: obj.file, // 上传文件对象
        onProgress: function(progressData) {
          // console.log(JSON.stringify(progressData))
          o.status = 'uploading'
          o.percentage = Math.floor(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) return
        o.status = 'success'
        o.url = 'http://' + data.Location
        console.log('上传成功')
      })
    }
  }

}
</script>

<style scoped lang='scss'>
.disabled{
  ::v-deep .el-upload--picture-card {
      display: none;
    }

}
</style>
